//
//  RegisterViewController.m
//  customer
//
//  Created by Holothurian on 2018/10/20.
//  Copyright © 2018年 yinlong. All rights reserved.
//

#import "RegisterViewController.h"
#import "RSA.h"

@interface RegisterViewController ()

@property (nonatomic,strong) UITextField *phoneTF;

@property (nonatomic,strong) UITextField *passWordTF;

@property (nonatomic,strong) UIButton *passwordSecure;

@property (nonatomic,strong)UITextField *surePasswordTF;

@property (nonatomic,strong) UIButton *surePasswordSecure;

@property (nonatomic,strong) UITextField *verifiTF;

@property (nonatomic,strong) UIButton *registButton;

@property (nonatomic,strong) UIButton *verifiButton;

@property (nonatomic,strong)dispatch_source_t labelTimer;

@property (nonatomic,assign)NSInteger numTime;



@property(nonatomic,strong)NSDate *backDate;//进入后台时的时间

@property(nonatomic,strong)NSDate *frontDate;//重新打开应用时的时间


@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"注册";
    self.numTime = 0;
    [self layoutUI];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setBackgroundTask) name:kRegisterBackgroundNoti object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setFrontTask) name:kRegisterFrontNoti object:nil];
    
}

- (void)setBackgroundTask{
    self.backDate = [NSDate date];
}

- (void)setFrontTask{
    self.frontDate = [NSDate date];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    if (self.labelTimer) {
        dispatch_suspend(self.labelTimer);//退出界面时，读秒还在进行中，这时候应该暂停该队列
    }
}

- (void)layoutUI{
    
    AutoWeakSelf
    //手机号
    UIView * phoneView = [UIView new];
    phoneView.layer.borderColor = [UIColor viewLayerGray].CGColor;
    phoneView.layer.borderWidth = 0.5f;
    phoneView.layer.cornerRadius = 4;
    phoneView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:phoneView];
    [phoneView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view.mas_top).offset(40+NAVIGATION_BAR_HEIGHT);
        make.left.equalTo(weakSelf.view.mas_left).offset(30*PROPORTION_WIDTH_IPHONE6);
        make.right.equalTo(weakSelf.view.mas_right).offset(-30*PROPORTION_WIDTH_IPHONE6);
        make.height.mas_equalTo(40);
    }];
    
    self.phoneTF = [UITextField new];
    self.phoneTF.placeholder = @"手机号";
    self.phoneTF.text = self.phoneStr;
    self.phoneTF.keyboardType = UIKeyboardTypeNumberPad;
    self.phoneTF.textColor = [UIColor blackColor];
    self.phoneTF.font = [UIFont systemFontOfSize:16];
    [self.phoneTF setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
    [phoneView addSubview:self.phoneTF];
    [self.phoneTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(phoneView).offset(10);
        make.top.bottom.right.equalTo(phoneView);
    }];
    
    //验证码
    
    UIView * verifiView = [UIView new];
    verifiView.layer.borderColor = [UIColor viewLayerGray].CGColor;
    verifiView.layer.borderWidth = 0.5f;
    verifiView.layer.cornerRadius = 4;
    verifiView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:verifiView];
    CGFloat phoneViewWidth = F_DEVICE_W - 60;
    [verifiView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view.mas_top).offset(95+NAVIGATION_BAR_HEIGHT);
        make.left.equalTo(weakSelf.view.mas_left).offset(30*PROPORTION_WIDTH_IPHONE6);
        make.width.mas_equalTo(phoneViewWidth * 0.55);
        make.height.mas_equalTo(40);
    }];
    
    self.verifiButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.verifiButton.titleLabel.font = [UIFont systemFontOfSize:16];
    self.verifiButton.layer.cornerRadius = 4;
    [self.verifiButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.verifiButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.verifiButton setBackgroundColor:RGBColor(51, 51, 51)];
    [self.verifiButton addTarget:self action:@selector(verifiButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.verifiButton];
    [self.verifiButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(weakSelf.view.mas_right).offset(-30*PROPORTION_WIDTH_IPHONE6);;
        make.top.equalTo(verifiView.mas_top).offset(0);
        make.size.mas_equalTo(CGSizeMake(phoneViewWidth * 0.4, 40));
    }];
    
    
    self.verifiTF = [UITextField new];
    self.verifiTF.placeholder = @"验证码";
    self.verifiTF.textColor = [UIColor blackColor];
    self.verifiTF.font = Font(16);
    self.verifiTF.keyboardType = UIKeyboardTypeNumberPad;
    [self.verifiTF setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
    [verifiView addSubview:self.verifiTF];
    [self.verifiTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(verifiView.mas_left).offset(10);
        make.top.equalTo(verifiView.mas_top).offset(0);
        make.size.mas_equalTo(CGSizeMake(phoneViewWidth * 0.55-10, 40));
    }];
    
    //密码
    UIView * pwView = [UIView new];
    pwView.layer.borderColor = [UIColor viewLayerGray].CGColor;
    pwView.layer.borderWidth = 0.5f;
    pwView.layer.cornerRadius = 4;
    pwView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:pwView];
    [pwView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(verifiView.mas_bottom).offset(15);
        make.left.right.equalTo(phoneView);
        make.height.mas_equalTo(40);
    }];
    
    self.passWordTF = [UITextField new];
    self.passWordTF.placeholder = @"密码";
    self.passWordTF.secureTextEntry = YES;
    self.passWordTF.textColor = [UIColor blackColor];
    self.passWordTF.font = [UIFont systemFontOfSize:16];
    [self.passWordTF setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
    [pwView addSubview:self.passWordTF];
    [self.passWordTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(pwView).offset(10);
        make.top.bottom.equalTo(pwView);
        make.width.mas_equalTo(phoneViewWidth - 50);
    }];
    
    self.passwordSecure = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.passwordSecure setImage:[UIImage imageNamed:@"hiddenPassword"] forState:UIControlStateNormal];
    [self.passwordSecure setImage:[UIImage imageNamed:@"showPassword"] forState:UIControlStateSelected];
    [self.passwordSecure addTarget:self action:@selector(passwordSecureAction:) forControlEvents:UIControlEventTouchUpInside];
    [pwView addSubview:self.passwordSecure];
    [self.passwordSecure mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(pwView).offset(10);
        make.right.equalTo(pwView.mas_right).offset(-10);
        make.size.mas_equalTo(CGSizeMake(20, 20));
    }];
    
    UIView * surePasswordView = [UIView new];
    surePasswordView.layer.borderColor = [UIColor viewLayerGray].CGColor;
    surePasswordView.layer.borderWidth = 0.5f;
    surePasswordView.layer.cornerRadius = 4;
    surePasswordView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:surePasswordView];
    [surePasswordView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(pwView.mas_bottom).offset(15);
        make.left.right.equalTo(phoneView);
        make.height.mas_equalTo(40);
    }];
    
    self.surePasswordTF = [UITextField new];
    self.surePasswordTF.placeholder = @"确认密码";
    self.surePasswordTF.secureTextEntry = YES;
    self.surePasswordTF.textColor = [UIColor blackColor];
    self.surePasswordTF.font = [UIFont systemFontOfSize:16];
    [self.surePasswordTF setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
    [surePasswordView addSubview:self.surePasswordTF];
    [self.surePasswordTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(surePasswordView).offset(10);
        make.top.bottom.equalTo(surePasswordView);
        make.width.mas_equalTo(phoneViewWidth - 50);
    }];
    
    self.surePasswordSecure = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.surePasswordSecure setImage:[UIImage imageNamed:@"hiddenPassword"] forState:UIControlStateNormal];
    [self.surePasswordSecure setImage:[UIImage imageNamed:@"showPassword"] forState:UIControlStateSelected];
    [self.surePasswordSecure addTarget:self action:@selector(surePasswordSecureAction:) forControlEvents:UIControlEventTouchUpInside];
    [surePasswordView addSubview:self.surePasswordSecure];
    [self.surePasswordSecure mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(surePasswordView).offset(10);
        make.right.equalTo(surePasswordView.mas_right).offset(-10);
        make.size.mas_equalTo(CGSizeMake(20, 20));
    }];
    
    
    
    //注册
    self.registButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.registButton.titleLabel.font = [UIFont systemFontOfSize:16];
    self.registButton.layer.cornerRadius = 10;
    self.registButton.layer.masksToBounds = YES;
    [self.registButton setBackgroundColor:[UIColor blackColor]];
    [self.registButton setTitle:@"注册" forState:UIControlStateNormal];
    [self.registButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.registButton addTarget:self action:@selector(registButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.registButton];
    [self.registButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(surePasswordView.mas_bottom).offset(112);
        make.left.equalTo(weakSelf.view).offset(15);
        make.right.equalTo(weakSelf.view).offset(-15);
        make.height.mas_equalTo(47);
    }];
    
}

- (void)passwordSecureAction:(UIButton *)sender{
    sender.selected = !sender.selected;
    self.passWordTF.secureTextEntry = !sender.selected;
}

- (void)surePasswordSecureAction:(UIButton *)sender{
    sender.selected = !sender.selected;
    self.surePasswordTF.secureTextEntry = !sender.selected;
    
}

//验证码

- (void)verifiButtonClick:(UIButton *)button{
    
    if (self.phoneTF.text.length != 11) {
        [self showErrorTipWithTitle:@"手机号码格式错误！"];
        return;
    }
    if (self.numTime>0) {
        [self showErrorTipWithTitle:@"2分钟内不可重复发送!"];
        return;
    }
    
    [self showLoading];
    AutoWeakSelf
    NSDictionary * par = @{@"mobile":[RSA encryptString:self.phoneTF.text publicKey:CustomerRsaPublicKey],@"code_type":[RSA encryptString:@"register" publicKey:CustomerRsaPublicKey]};
    [[QYNetManager sharedManager]POST:kSendCode parameters:par andApiTyp:CustomerApiTypMain SuccessBlock:^(id responseObject) {
        [weakSelf hideLoading];
        NSString * statusStr = [NSString stringWithFormat:@"%@",responseObject[@"status"]];
        if ([statusStr isEqualToString:@"ok"]) {
            weakSelf.numTime = 120;
            [weakSelf getStartTime];
        }else{
            NSString * errorStr = [NSString stringWithFormat:@"%@",responseObject[@"error"]];
            [weakSelf showErrorTipWithTitle:errorStr];
        }
    } Failure:^(NSError *error) {
        [weakSelf hideLoading];
        [weakSelf showErrorTipWithTitle:error.localizedDescription];
    }];
    
    
}

//注册
- (void)registButtonClick:(UIButton *)button{
    
    if (self.phoneTF.text.length != 11) {
        [self showErrorTipWithTitle:@"请输入11位数的手机号"];
        return;
    }
    
    if (self.verifiTF.text.length != 6 || ![self.verifiTF.text isNumber]) {
        [self showErrorTipWithTitle:@"验证码错误"];
        return;
    }
    if (self.passWordTF.text.length < 6 || self.passWordTF.text.length > 16) {
        [self showErrorTipWithTitle:@"请输入6-16位密码"];
        return;
    }
    if (![self.passWordTF.text isEqualToString:self.surePasswordTF.text]) {
        [self showErrorTipWithTitle:@"密码不一致"];
        return;
    }
    [self showLoading];
    NSDictionary * par = @{@"member_account":self.phoneTF.text,@"member_password":self.passWordTF.text,@"code":self.verifiTF.text,@"member_type":@"1"};
    [[QYNetManager sharedManager]POST:kRegisterMember parameters:par andApiTyp:CustomerApiTypMain SuccessBlock:^(id responseObject) {
        [self hideLoading];
        NSString * statusStr = [NSString stringWithFormat:@"%@",responseObject[@"status"]];
        if ([statusStr isEqualToString:@"ok"]) {
            [self showTipWithTitle:@"注册成功"];
            [self performSelector:@selector(backLogin) withObject:nil afterDelay:1.0f];
        }else{
            NSString * errorStr = [NSString stringWithFormat:@"%@",responseObject[@"error"]];
            [self showErrorTipWithTitle:errorStr];
        }
    } Failure:^(NSError *error) {
        [self hideLoading];
        [self showErrorTipWithTitle:error.localizedDescription];
    }];
    
}

- (void)backLogin{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 定时器
//开启定时器
- (void)getStartTime{
     dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
     self.labelTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
      dispatch_source_set_timer(self.labelTimer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
      AutoWeakSelf
      dispatch_source_set_event_handler(self.labelTimer, ^{
               if(self.numTime<=0){ //倒计时结束，关闭
                    dispatch_source_cancel(weakSelf.labelTimer);
                     dispatch_async(dispatch_get_main_queue(), ^{
                        // 时间到，停止动作
                        [weakSelf destoryLabelTimer];
                        [weakSelf.verifiButton setTitle:@"重新获取" forState:UIControlStateNormal];
                        weakSelf.verifiButton.userInteractionEnabled = YES;
                        [weakSelf.verifiButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                          });
                   }else{
                            if (weakSelf.frontDate&&weakSelf.backDate) {   //这里面就是判断进出应用两次之间的时间差
                                   NSTimeInterval backDate = [weakSelf.backDate timeIntervalSinceReferenceDate];
                                   NSTimeInterval frontDate = [weakSelf.frontDate timeIntervalSinceReferenceDate];
                                   int interval = frontDate - backDate;
                                   weakSelf.numTime = weakSelf.numTime - interval;
                                   weakSelf.backDate = nil;
                                   weakSelf.frontDate = nil;
                            }
                           NSInteger seconds = weakSelf.numTime % 121;
                           dispatch_async(dispatch_get_main_queue(), ^{
                                //NSLog(@"每秒执行一次");
                                weakSelf.verifiButton.userInteractionEnabled = NO;
                                [weakSelf.verifiButton setTitle:[NSString stringWithFormat:@"%ld",seconds] forState:UIControlStateNormal];
                            });
                            weakSelf.numTime--;
                      }
            });
        dispatch_resume(self.labelTimer);
    
}

//销毁定时器
- (void)destoryLabelTimer{
    if (self.labelTimer) {
        self.labelTimer = nil;
    }
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
